from common.config import conf

from celery import Celery
from celery.schedules import crontab


class CeleryApp(object):
    def __init__(self):
        self.celery_app = Celery("celery_task")
        self.celery_app.conf.update(
            broker_url=conf["rabbitmq"]["broker_url"],
            result_backend=conf["rabbitmq"]["result_backend"],
            accept_content=["json"],
            task_serializer="json",
            result_serializer="json",
            # 一个取一个任务
            worker_prefetch_multiplier=1,
            # 执行完40个任务后自动销毁，避免内存泄漏
            worker_max_tasks_per_child=40,
            # 结果消息失效时间一小时
            result_expires=1 * 60 * 60,
            # 同时工作的worker数
            worker_concurrency=10,
            # 任务超时时间
            task_time_limit=60*60,
            task_track_started=True,
            imports=(
                'web_api.service.task_service',
            ),
            task_queues=(
                Queue(
                    name='important_server_monitor',
                    exchange=Exchange('important_server_monitor'),
                    routing_key='important_server_monitor'
                ),
            ),
            taks_routes={
                'monitor.monitor_task.abnormal_server_task':
                    {
                        "queue": 'abnormal_server_tasks',
                        "exchange": 'abnormal_server_tasks',
                        "routing_key": 'abnormal_server_tasks',
                    },
            },

            # celery时区，定时任务需要
            enable_utc=True,
            timezone='Asia/Shanghai',
            # 每天零点一分执行;一天一小时执行一次
            beat_schedule={
                "daily_beat":
                    {
                        "task": "monitor_entrance",
                        "schedule": crontab(minute=1, hour=0),
                        "options": {
                            "queue": 'abnormal_server_tasks',
                            "exchange": 'abnormal_server_tasks',
                            "routing_key": 'abnormal_server_tasks',
                        }
                    },
                "abnormal_server_monitor":
                    {
                        "task": "monitor_entrance",
                        "schedule": timedelta(minute=1),
                        "options": {
                            "queue": 'abnormal_server_tasks',
                            "exchange": 'abnormal_server_tasks',
                            "routing_key": 'abnormal_server_tasks',
                        }
                    },
            }

        )


celery_app = CeleryApp().celery_app
